package com.jming.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jming.yygh.common.exception.YyghException;
import com.jming.yygh.common.helper.JwtHelper;
import com.jming.yygh.common.result.ResultCodeEnum;
import com.jming.yygh.enums.AuthStatusEnum;
import com.jming.yygh.model.user.Patient;
import com.jming.yygh.model.user.UserInfo;
import com.jming.yygh.user.mapper.UserInfoMapper;
import com.jming.yygh.user.service.PatientService;
import com.jming.yygh.user.service.UserInfoService;
import com.jming.yygh.vo.user.LoginVo;
import com.jming.yygh.vo.user.UserAuthVo;
import com.jming.yygh.vo.user.UserInfoQueryVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jming
 * @version 0.0.1
 * @date 2021/05/08
 */
@Service
public class UserInfoServiceImpl
        extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    PatientService patientService;

    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {

        // 从loginVo获取输入的手机号
        String phone = loginVo.getPhone().trim();
        String code = loginVo.getCode().trim();

        // 判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        // 判断手机验证码和输入的验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        // 绑定手机号
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        if (userInfo == null) {
            // 判断是否第一次登录：根据手机号查询数据库，如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) { // 如果为空，则说明是第一次使用这个手机号
                // 将数据添加到数据库
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        // 校验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        // 如果不是第一次登录，直接登录，返回登录信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }

        // 返回登录用户名
        map.put("name", name);
        // 返回token信息，jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {

        // 根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        // 设置用户认证信息系
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //进行更新用户信息
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageparam, UserInfoQueryVo userInfoQueryVo) {

        // userInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword();  // 用户名称
        Integer status = userInfoQueryVo.getStatus(); // 用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();  // 认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); // 开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();  // 结束时间

        // 对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("update_time", createTimeEnd);
        }

        // 调用方法
        Page<UserInfo> pages = baseMapper.selectPage(pageparam, wrapper);
        // 将编号变成对应的值
        pages.getRecords().stream().forEach (item ->
            this.packegeUserInfo(item));

        return pages;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {

        Map<String, Object> map = new HashMap<>();

        // 根据用户id查询用户信息
        UserInfo userInfo = this.packegeUserInfo(baseMapper.selectById(userId));
        map.put("userInfo", userInfo);

        // 根据用户id 查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList", patientList);

        return map;
    }

    @Override
    public void approvar(Long userId, Integer authStatus) {
        if (authStatus.intValue() == 2 || authStatus.intValue() == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    // 将编号变成对应的值
    private UserInfo packegeUserInfo(UserInfo userInfo) {
        // 处理认证状态
        userInfo.getParam().put("authStatusString",
                AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        // 处理用户状态
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;

    }
}
